package com.yshebkb.sulp.controller;

import com.yshebkb.sulp.domain.RestResponse;
import com.yshebkb.sulp.domain.UserView;
import com.yshebkb.sulp.entity.Menu;
import com.yshebkb.sulp.entity.User;
import com.yshebkb.sulp.exception.AppException;
import com.yshebkb.sulp.service.MenuService;
import com.yshebkb.sulp.service.UserService;
import com.yshebkb.sulp.utils.ShiroUtils;
import com.yshebkb.sulp.exception.ErrorCodes;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author yshebkb
 * @date 2018/7/29
 */
@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private MenuService menuService;

    @RequestMapping("/list")
    @ResponseBody
    public RestResponse userList() {
        return RestResponse.success(userService.findAll().stream().map(UserView::new).collect(Collectors.toList()));
    }

    @RequestMapping("/create")
    public String addUser(@RequestBody User user) {
        User dbUser = userService.findUserByUsername(user.getName());
        if (dbUser == null) {
            throw new AppException(ErrorCodes.ACCOUNT_ALREADY_EXISTS);
        }
        userService.save(user);
        return "保存成功";
    }

    @RequestMapping("/check/{name}")
    public boolean checkName(@PathVariable String name){
        User user = userService.findUserByUsername(name);
        return user == null;
    }

    @RequestMapping(value = "/modify", method = {RequestMethod.POST})
    public RestResponse modifyUser(@RequestBody User user) {
        userService.updateUser(user);
        return RestResponse.success("修改成功");
    }

    @RequestMapping("/delete/{id}")
    public String delUser(@PathVariable Long id) {
        userService.deleteById(id);
        return "删除成功";
    }

    @RequestMapping(value = "/menu")
    public List<Menu> menu() {
        return menuService.getRootMenus(ShiroUtils.getUserName());
    }

    @RequestMapping("/perms")
    public Set<String> getPerms() {
        Subject subject = ShiroUtils.getSubject();
        User user = (User) subject.getPrincipal();
        Long userId = user.getId();
        return userService.getPerms(userId);
    }


}
